from django import forms
from django.core.exceptions import ValidationError

from .models import Comment


class CommentForm(forms.ModelForm):
    def clean_comment_parent(self):
        data = self.cleaned_data.get('comment_parent')
        # 如果没有提供父评论，则返回 None，表示这是一级评论
        if not data:
            return None
        # 如果提供了父评论 ID，则尝试获取对应的 Comment 对象
        try:
            # 确保 'data' 是一个整数
            if isinstance(data, Comment):
                data = data.pk
            comment = Comment.objects.get(pk=data)
        except Comment.DoesNotExist:
            raise ValidationError("Invalid comment parent ID. This comment does not exist.")
        return comment

    class Meta:
        model = Comment
        fields = ['content', 'author', 'email', 'url', 'article', 'comment_parent']
